package com.tpp.threat_perception_platform.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tpp.threat_perception_platform.dao.AppMapper;
import com.tpp.threat_perception_platform.param.MyParam;
import com.tpp.threat_perception_platform.pojo.App;
import com.tpp.threat_perception_platform.response.ResponseResult;
import com.tpp.threat_perception_platform.service.AppService;
import com.tpp.threat_perception_platform.service.RiskAssessmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.List;

@Service
public class AppServiceImpl implements AppService {

    @Autowired
    private AppMapper appMapper;

    @Autowired
    private RiskAssessmentService riskAssessmentService; // 注入统一风险评估服务

    @Transactional
    @Override
    public int saveApp(App app) {
        int count = appMapper.countByMacAddress(app.getMacAddress());
        app.setCreateTime(new Timestamp(System.currentTimeMillis()));
        return appMapper.insertSelective(app);
    }

    @Override
    public void deleteByMacAddress(String macAddress) {
        appMapper.deleteByMacAddress(macAddress);
    }

    @Override
    public ResponseResult appList(MyParam param) {
        PageHelper.startPage(param.getPage(), param.getLimit());

        List<App> dataList = appMapper.findAll(param);

        for (App app : dataList) {
            String riskLevel = riskAssessmentService.assess(app); // 统一调用
            app.setRiskLevel(riskLevel);
            appMapper.updateRiskLevelByMacAddress(app.getMacAddress(), riskLevel); // 可选写回数据库
        }

        PageInfo<App> pageInfo = new PageInfo<>(dataList);
        return new ResponseResult<>(pageInfo.getTotal(), pageInfo.getList());
    }
}
